﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using AutoMapper;
using H2.NET.Business;
using H2.NET.Common;
using H2.NET.TaskRob;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Data.Common;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Workflow.Helper;
using System.Text;
using NPOI.SS.Formula.Functions;

namespace H2.NET.Web.Pages.SMD
{
    public partial class DepositChange : BasePage
    {
        public List<string> InOptions = new List<string>();
        public List<string> OutOptions = new List<string>();
        private string key;

        protected void Page_Load(object sender, EventArgs e)
        {
            var taskid = Request.QueryString["taskid"];
            key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
            // 重定向
            if (key == Constant.PROCESS_BATCHDEPOSIT)
            {
                Response.Redirect("BatchDepositChange.aspx?taskid=" + taskid);
            }
            DwzAssessment1.remark = "变更原因";
            uc_dealer_in.d_title = "进款经销商";
            uc_dealer_in.dealerCallBack = "dealerInCallBack";
            uc_dealer_in.dealer = new t_smd_Dealer();
            uc_dealer_out.d_title = "退款经销商";
            uc_dealer_out.dealerCallBack = "dealerOutCallBack";
            uc_dealer_out.dealer = new t_smd_Dealer();


            var configService = new ConfigService();

            // 进款选项
            var dt = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_DEPOSIT_IN') order by seq").Tables[0];
            foreach (DataRow row in dt.Rows)
            {
                InOptions.Add(row["name"].ToString());
            }
            // 退款选项
            dt = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_DEPOSIT_OUT') order by seq").Tables[0];
            foreach (DataRow row in dt.Rows)
            {
                OutOptions.Add(row["name"].ToString());
            }

            if (!IsPostBack)
            {
                if (key == Constant.PROCESS_CHANGEOTHER)
                {
                    uc_dealer_in.Visible = false;
                    inTitle.Visible = false;
                    inList.Visible = false;
                }

                if (ReadOnly()) return;

                dt = configService.GetList("ParentId = (select configid from t_smd_Config where code='M_MDQY') order by seq").Tables[0];
                ddl_region.AppendDataBoundItems = true;
                ddl_region.Items.Add(new ListItem("==请选择==", ""));
                ddl_region.DataValueField = "Name";
                ddl_region.DataTextField = "Name";
                ddl_region.DataSource = dt;
                ddl_region.DataBind();

                #region 表单是否占用

                if (IsOverFlow)
                {
                    btn_submit.Visible = false;
                    JsTip(string.Format("该表单正在被“{0}”处理，请稍后再试。", RobUser));
                    return;
                }

                #endregion

                #region “Fill in the form”、“Submit Document”步骤

                if (TaskAPI.Step == "Fill in the request" || TaskAPI.Step == "Submit Document")
                {
                    uc_dealer_in.IsCanEditAuthID = false;
                    uc_dealer_in.isCanChoose = true;
                    uc_dealer_out.IsCanEditAuthID = false;
                    uc_dealer_out.isCanChoose = true;

                    // 经销商更换
                    var autoBusinessKey = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                    switch (autoBusinessKey)
                    {
                        case Constant.PROCESS_CHANGEDEALER:
                            InitChangeDealer();
                            break;
                        case Constant.PROCESS_TRANSFER:
                            InitChangeTransfer();
                            break;
                        case Constant.PROCESS_CHANGESTATUS:
                            InitChangeStatus();
                            break;
                        case Constant.PROCESS_CHANGEOTHER:
                            InitChangeOther();
                            break;
                    }

                    //如果退回就显示审批列表
                    if (!String.IsNullOrEmpty(TaskAPI.GetVariableBySingleValue("Changed")))
                    {
                        assessment.Visible = true;
                    }
                }
                #endregion

                #region 审核页面初始化

                else
                {
                    assessment.Visible = true;
                    var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                    if (storeMasterData == null)
                    {
                        btn_submit.Visible = false;
                        JsTip("加载数据失败，请关闭页面重新打开！");
                        return;
                    }
                    if (storeMasterData.PcModel != null && storeMasterData.PcModel == "True")
                    {
                        DwzAssessment1.Cashier = true;
                    }

                    hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                    hl_ExportPdf.Visible = true;

                    uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                    if (storeMasterData.SubmitDate != null)
                        uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");
                    uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");

                    uc_dealer_in.IsCanEditAuthID = false;
                    uc_dealer_in.isCanChoose = false;
                    uc_dealer_out.IsCanEditAuthID = false;
                    uc_dealer_out.isCanChoose = false;

                    l_area.Text = storeMasterData.AreaName + @" , " + storeMasterData.ProvinceName;
                    ddl_region.Visible = false;
                    ddl_province.Visible = false;

                    // 获取变更数据
                    var assessments = AssessmentService.FindByPI(TaskAPI.Process, TaskAPI.Incident);
                    var depositTrans = DepositTranService.FindInAssIds(assessments.Select(t => t.ID).ToList());

                    // 进款经销商
                    if (!string.IsNullOrEmpty(storeMasterData.DispenseModel))
                    {
                        var dealerId = Utils.StrToInt(storeMasterData.DispenseModel, 0);
                        if (dealerId > 0)
                        {
                            uc_dealer_in.dealer = DealerService.GetById(dealerId);
                            in_tbody.InnerHtml = FormatHtml(depositTrans, dealerId, "in");
                        }
                    }

                    // 退款经销商
                    if (!string.IsNullOrEmpty(storeMasterData.ShakerModel))
                    {
                        var dealerId = Utils.StrToInt(storeMasterData.ShakerModel, 0);
                        if (dealerId > 0)
                        {
                            uc_dealer_out.dealer = DealerService.GetById(dealerId);
                            out_tbody.InnerHtml = FormatHtml(depositTrans, dealerId, "out");
                        }
                    }

                    // 经销商变更、读取进款的经销商ID（因为设备已转掉）
                    var autoBusinnessKey = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                    if (autoBusinnessKey == Constant.PROCESS_CHANGEDEALER || autoBusinnessKey == Constant.PROCESS_TRANSFER)
                    {
                        var dealerId = Utils.StrToInt(storeMasterData.DispenseModel, 0);
                        if (dealerId > 0)
                        {
                            uc_dealer_in.dealer = DealerService.GetById(dealerId);
                            out_tbody.InnerHtml = FormatHtml(depositTrans, dealerId, "out");
                        }
                    }
                }
                //
                #endregion
            }
        }

        #region 只读表单

        private bool ReadOnly()
        {
            if (AksRequest.GetString("readonly") == "1")
            {
                // 只读表单，释放抢占
                OpenTasksInstance.OpenTasks.SetTaskClose(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);

                assessment.Visible = true;
                btn_submit.Visible = false;
                ajaxUpload1.AllowUpload = false;
                ajaxUpload1.AllowDelete = false;
                DwzAssessment1.Visible = false;

                var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                if (storeMasterData == null)
                {
                    JsTip("该流程还没有提交过，没有任何数据！");
                    return true;
                }

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                if (storeMasterData.SubmitDate != null)
                    uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");

                uc_dealer_in.IsCanEditAuthID = false;
                uc_dealer_in.isCanChoose = false;
                uc_dealer_out.IsCanEditAuthID = false;
                uc_dealer_out.isCanChoose = false;

                l_area.Text = storeMasterData.AreaName + @" , " + storeMasterData.ProvinceName;
                ddl_region.Visible = false;
                ddl_province.Visible = false;

                // 获取变更数据
                var assessments = AssessmentService.FindByPI(TaskAPI.Process, TaskAPI.Incident);
                var depositTrans = DepositTranService.FindInAssIds(assessments.Select(t => t.ID).ToList());

                // 进款经销商
                if (!string.IsNullOrEmpty(storeMasterData.DispenseModel))
                {
                    var dealerId = Utils.StrToInt(storeMasterData.DispenseModel, 0);
                    if (dealerId > 0)
                    {
                        uc_dealer_in.dealer = DealerService.GetById(dealerId);
                        in_tbody.InnerHtml = FormatHtml(depositTrans, dealerId, "in", true);
                    }
                }

                // 退款经销商
                if (!string.IsNullOrEmpty(storeMasterData.ShakerModel))
                {
                    var dealerId = Utils.StrToInt(storeMasterData.ShakerModel, 0);
                    if (dealerId > 0)
                    {
                        uc_dealer_out.dealer = DealerService.GetById(dealerId);
                        out_tbody.InnerHtml = FormatHtml(depositTrans, dealerId, "out", true);
                    }
                }

                //// 经销商变更、读取进款的经销商ID（因为设备已转掉）
                //var autoBusinnessKey = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                //if (autoBusinnessKey == Constant.PROCESS_CHANGEDEALER || autoBusinnessKey == Constant.PROCESS_TRANSFER)
                //{
                //    var dealerId = Utils.StrToInt(storeMasterData.DispenseModel, 0);
                //    if (dealerId > 0)
                //    {
                //        uc_dealer_in.dealer = DealerService.GetById(dealerId);
                //        out_tbody.InnerHtml = FormatHtml(depositTrans, dealerId, "out",true);
                //    }
                //}

                hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                hl_ExportPdf.Visible = true;
                btn_print.Visible = true;
                cb_isFinanceConfirm.Visible = false;
                l_isFinanceConfirm.Text = storeMasterData.PcModel == "True" ? "需要" : "不需要";

                #region 验证是否选择退至客户银行账户--必须要财务确认

                var list = depositTrans.Where(d => d.TranType == "退至客户银行账号").ToList();
                if (list.Count > 0 && !cb_isFinanceConfirm.Checked)
                {
                    //cb_isFinanceConfirm.Visible = true;
                    //cb_isFinanceConfirm.Enabled = false;
                    cb_isFinanceConfirm.Checked = true;
                    storeMasterData.PcModel = "True";
                    l_isFinanceConfirm.Text = "需要";
                }

                #endregion

                return true;
            }

            return false;
        }
        #endregion

        #region 画面初始化

        /// <summary>
        /// 初始化“经销商变更”保证金变更页面
        /// </summary>
        private void InitChangeDealer()
        {
            var region = TaskAPI.GetVariableBySingleValue("Region");
            var province = TaskAPI.GetVariableBySingleValue("Province");
            var blankVlue = TaskAPI.GetVariableBySingleValue("BlankVlue");
            var split = blankVlue.Split('|');
            var dealerIdNew = Utils.StrToInt(split[0], 0);
            var dealerIdOld = Utils.StrToInt(split[1], 0);

            uc_dealer_in.IsCanEditAuthID = false;
            uc_dealer_in.isCanChoose = false;
            uc_dealer_in.dealer = DealerService.GetById(dealerIdNew);
            uc_dealer_out.IsCanEditAuthID = false;
            uc_dealer_out.isCanChoose = false;
            uc_dealer_out.dealer = DealerService.GetById(dealerIdOld);

            ddl_region.Items.Clear();
            ddl_region.Items.Add(new ListItem(region, region));
            ddl_region.Visible = false;
            ddl_province.Items.Clear();
            ddl_province.Items.Add(new ListItem(province, province));
            ddl_province.Visible = false;
            l_area.Text = region + @" , " + province;

            var deviceIds = GetDeviceIds();
            // 进款经销商
            in_tbody.InnerHtml = FormatHtml(dealerIdNew, "in", deviceIds);
            // 退款经销商 （要显示dealerId_new的设备）
            out_tbody.InnerHtml = FormatHtml(dealerIdNew, "out", deviceIds);
        }

        /// <summary>
        /// 初始化“设备三方转移”保证金变更页面
        /// </summary>
        private void InitChangeTransfer()
        {
            var region = TaskAPI.GetVariableBySingleValue("Region");
            var province = TaskAPI.GetVariableBySingleValue("Province");
            var blankVlue = TaskAPI.GetVariableBySingleValue("BlankVlue"); // 选择的设备id | 转出的门店id | 转入的门店id
            var split = blankVlue.Split('|');
            var deviceId = split[0];
            var outStoreId = split[1];
            var inStoreId = split[2];

            var storeNew = StoreService.GetSmdStoreById(Utils.StrToInt(inStoreId, 0));
            var storeOld = StoreService.GetSmdStoreById(Utils.StrToInt(outStoreId, 0));
            var dealerIdNew = storeNew.DealerID == null ? 0 : storeNew.DealerID.Value;
            var dealerIdOld = storeOld.DealerID == null ? 0 : storeOld.DealerID.Value;

            uc_dealer_in.IsCanEditAuthID = false;
            uc_dealer_in.isCanChoose = false;
            uc_dealer_in.dealer = DealerService.GetById(dealerIdNew);
            uc_dealer_out.IsCanEditAuthID = false;
            uc_dealer_out.isCanChoose = false;
            uc_dealer_out.dealer = DealerService.GetById(dealerIdOld);

            ddl_region.Items.Clear();
            ddl_region.Items.Add(new ListItem(region, region));
            ddl_region.Visible = false;
            ddl_province.Items.Clear();
            ddl_province.Items.Add(new ListItem(province, province));
            ddl_province.Visible = false;
            l_area.Text = region + @" , " + province;

            // 进款经销商
            in_tbody.InnerHtml = FormatHtml(dealerIdNew, "in", new List<int> { Utils.StrToInt(deviceId, 0) });
            // 退款经销商 （要显示dealerId_new的设备、要显示转出的经销商的设备、并且要读取原来经销商的设备保证金）
            out_tbody.InnerHtml = FormatHtml(dealerIdNew, "out", new List<int> { Utils.StrToInt(deviceId, 0) });
        }

        /// <summary>
        /// 初始化“设备报废”保证金变更页面
        /// </summary>
        private void InitChangeStatus()
        {
            var region = TaskAPI.GetVariableBySingleValue("Region");
            var province = TaskAPI.GetVariableBySingleValue("Province");
            var deviceid = TaskAPI.GetVariableBySingleValue("DeviceID");
            var storeid = TaskAPI.GetVariableBySingleValue("BlankVlue");
            var store = StoreService.GetSmdStoreById(Utils.StrToInt(storeid, 0));
            var dealer = DealerService.GetById(store.DealerID == null ? 0 : store.DealerID.Value);

            uc_dealer_in.IsCanEditAuthID = false;
            uc_dealer_in.isCanChoose = false;
            uc_dealer_out.IsCanEditAuthID = false;
            uc_dealer_out.isCanChoose = false;
            uc_dealer_out.dealer = dealer;

            ddl_region.Items.Clear();
            ddl_region.Items.Add(new ListItem(region, region));
            ddl_region.Visible = false;
            ddl_province.Items.Clear();
            ddl_province.Items.Add(new ListItem(province, province));
            ddl_province.Visible = false;
            l_area.Text = region + @" , " + province;

            // 退款经销商
            out_tbody.InnerHtml = FormatHtml(dealer.DealerID, "out", new List<int> { Utils.StrToInt(deviceid, 0) });
        }


        /// <summary>
        /// 初始化批量保证金变更页面
        /// </summary>
        private void InitChangeOther()
        {
            var region = TaskAPI.GetVariableBySingleValue("Region");
            var province = TaskAPI.GetVariableBySingleValue("Province");
            ddl_region.Items.Clear();
            ddl_region.Items.Add(new ListItem(region, region));
            ddl_region.Visible = false;
            ddl_province.Items.Clear();
            ddl_province.Items.Add(new ListItem(province, province));
            ddl_province.Visible = false;
            l_area.Text = region + @" , " + province;
            if (TaskAPI.Summary.Contains("退回"))
            {
                var blankVlue = TaskAPI.GetVariableBySingleValue("BlankVlue");

                var dealerIdOld = Utils.StrToInt(blankVlue, 0);

                uc_dealer_out.IsCanEditAuthID = false;
                uc_dealer_out.isCanChoose = false;
                uc_dealer_out.dealer = DealerService.GetById(dealerIdOld);

                ddl_region.Items.Clear();
                ddl_region.Items.Add(new ListItem(region, region));
                ddl_region.Visible = false;
                ddl_province.Items.Clear();
                ddl_province.Items.Add(new ListItem(province, province));
                ddl_province.Visible = false;
                l_area.Text = region + @" , " + province;

                var deviceIds = GetDeviceIds();

                // 退款经销商 （要显示dealerId_new的设备）
                out_tbody.InnerHtml = FormatHtml(dealerIdOld, "out", deviceIds);
            }
        }

        /// <summary>
        /// 初始化审核画面
        /// </summary>
        private string FormatHtml(List<t_StoreDepositTran> depositTrans, int dealerId, string type, bool readOnly = false)
        {
            // 过滤进款、退款
            List<string> options;
            if (type == "in")
            {
                depositTrans = depositTrans.Where(t => t.DepositType == "进款" && t.Amount > 0).ToList();
                options = InOptions;
            }
            else
            {
                if (key == Constant.PROCESS_CHANGEOTHER)
                {
                    depositTrans = depositTrans.Where(t => t.DepositType == "返还").ToList();
                }
                else
                {
                    depositTrans = depositTrans.Where(t => t.DepositType == "退款" && t.Amount > 0).ToList();
                }

                options = OutOptions;
            }

            // 生成Html，dealerdeposit=经销商下的每个设备
            var htmlBuilder = new StringBuilder();
            var deviceIds = depositTrans.Select(t => t.DeviceID).ToList();

            // 获取所有关联数据
            var dealerdeposits = DepositService.FindByDealerIdAndStoreIds(dealerId, null);
            dealerdeposits = dealerdeposits.Where(dealerdeposit => deviceIds.Contains(dealerdeposit.DeviceID)).Distinct().ToList();
            if (readOnly)
            {

                foreach (var depositran in depositTrans)
                {
                    var autoBusinessKey = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                    var device = DeviceService.GetSmdDeviceById(depositran.DeviceID.Value);
                    if (autoBusinessKey == Constant.PROCESS_TRANSFER && type == "out")
                    {
                        var blankVlue = TaskAPI.GetVariableBySingleValue("BlankVlue"); // 选择的设备id | 转出的门店id | 转入的门店id
                        var split = blankVlue.Split('|');
                        var deviceId = split[0];
                        var outStoreId = Utils.StrToInt(split[1], 0);
                        var store = StoreService.GetSmdStoreById(outStoreId);
                        var amount = "";


                        var existingDeviceChangelogs =
                        ChangeLogService.GetLastSmdChangeLogs(TaskAPI).Where(t => t.Category == "DepositChange" & t.DataID == depositran.DeviceID.ToString()).ToList();
                        if (existingDeviceChangelogs.Count > 0)
                        {
                            amount = existingDeviceChangelogs[0].BeforeValue;
                        }
                        else
                        {
                            var deposit = (v_DeviceDeposit._DeviceID == depositran.DeviceID).ListFirst<v_DeviceDeposit>(Storage.Context3,
                            " DepositID desc");
                            if (deposit != null)
                            {
                                amount = (deposit.Amount ?? 0).ToString("N");
                            }
                        }



                        htmlBuilder.AppendLine("<tr>");
                        htmlBuilder.AppendLine("     <td align='center' style='display:none'>[" + store.AuthID + "]" + store.StoreName + "</td>");
                        htmlBuilder.AppendLine("     <td align='center' style='padding:0 5px;'>" + device.FullSetSN + "</td>");
                        htmlBuilder.AppendLine("     <td align='center' style='padding:0 5px;'>" + amount + "</td>");

                    }
                    else
                    {
                        string amount = "0.0";
                        //var 
                        if (type == "out")
                        {
                            var existingDeviceChangelogs =
                            ChangeLogService.GetLastSmdChangeLogs(TaskAPI).Where(t => t.Category == "DepositChange" & t.DataID == depositran.DeviceID.ToString()).ToList();
                            if (existingDeviceChangelogs.Count > 0)
                            {
                                amount = existingDeviceChangelogs[0].BeforeValue;
                            }
                            else
                            {
                                var deposit = (v_DeviceDeposit._DeviceID == depositran.DeviceID).ListFirst<v_DeviceDeposit>(Storage.Context3,
                                   " DepositID desc");
                                var _device = DeviceService.GetSmdDeviceById(depositran.DeviceID.Value);
                                if (deposit != null)
                                {
                                    amount = (deposit.Amount ?? 0).ToString("N");

                                }
                                if (_device != null && _device.Status == "报废")
                                {
                                    amount = (DepositService.GetDeviceDeposit(depositran.DeviceID.Value).Amount).ToString("N");
                                }

                            }
                        }
                        var outstore = StoreService.GetSmdStoreById(depositran.StoreID);

                        htmlBuilder.AppendLine("<tr>");
                        htmlBuilder.AppendLine("     <td align='center' style='display:none'>[" + outstore.AuthID + "]" + outstore.StoreName + "</td>");
                        htmlBuilder.AppendLine("     <td align='center' style='padding:0 5px;'>" + device.FullSetSN + "</td>");
                        htmlBuilder.AppendLine("     <td align='center' style='padding:0 5px;'>" + amount + "</td>");
                    }
                    // 遍历变更类型
                    foreach (var option in options)
                    {
                        var depositTran = depositTrans.FirstOrDefault(t => t.DeviceID == depositran.DeviceID && t.TranType == option);

                        if (depositTran != null && !string.IsNullOrEmpty(depositTran.TranType))
                        {
                            if (depositTran.Amount == null) continue;
                            var amount = depositTran.Amount.Value.ToString("N");
                            var reason = depositTran.Reason;

                            switch (depositTran.TranType)
                            {
                                case "退至客户银行账号":
                                case "汇入营业外收入":
                                case "转营业外收入":
                                    htmlBuilder.AppendLine("     <td align='center'>" + amount + reason + "</td>");
                                    break;
                                //case "进款凭证号码":
                                //case "退款凭证号码":
                                //    htmlBuilder.AppendLine(TaskAPI.Step == "Finance Change" ? "<td align='center'><input type='text' name='" + type + "_option[" + depositran.DeviceID + "]' value='" + reason + "' /></td>" : "     <td align='center'>" + reason + "</td>");
                                //    break;
                                default:
                                    htmlBuilder.AppendLine("     <td align='center'>" + amount + "</td>");
                                    break;
                            }
                        }
                        else
                        {
                            if (TaskAPI.Step == "Finance Change" && (option == "进款凭证号码" || option == "退款凭证号码"))
                            {
                                htmlBuilder.AppendLine("     <td align='center'><input type='text' name='" + type + "_option[" + depositran.DeviceID + "]' /></td>");
                            }
                            else
                            {
                                htmlBuilder.AppendLine("     <td align='center'></td>");
                            }
                        }
                    }
                    htmlBuilder.AppendLine("</tr>");
                }
            }
            else
            {
                foreach (var dealerdeposit in dealerdeposits)
                {
                    // 如果是设备三方转移、需要读取一下原来的保证金
                    var autoBusinessKey = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                    if (autoBusinessKey == Constant.PROCESS_TRANSFER && type == "out")
                    {
                        var blankVlue = TaskAPI.GetVariableBySingleValue("BlankVlue"); // 选择的设备id | 转出的门店id | 转入的门店id
                        var split = blankVlue.Split('|');
                        var deviceId = split[0];
                        var outStoreId = Utils.StrToInt(split[1], 0);
                        var store = StoreService.GetSmdStoreById(outStoreId);
                        var amount = "";
                        var deposit = (v_DeviceDeposit._DeviceID == deviceId).ListFirst<v_DeviceDeposit>(Storage.Context3,
                            " DepositID desc");
                        if (deposit != null)
                        {
                            dealerdeposit.Amount = deposit.Amount ?? 0;
                            amount = dealerdeposit.Amount.ToString("N");
                        }

                        amount = dealerdeposit.Amount.ToString("N");
                        var existingDeviceChangelogs =
                        ChangeLogService.GetLastSmdChangeLogs(TaskAPI).Where(t => t.Category == "DepositChange" & t.DataID == dealerdeposit.DeviceID.ToString()).ToList();
                        if (existingDeviceChangelogs.Count > 0)
                        {
                            amount = existingDeviceChangelogs[0].BeforeValue;
                        }

                        htmlBuilder.AppendLine("<tr>");
                        htmlBuilder.AppendLine("     <td align='center' style='display:none'>[" + store.AuthID + "]" + store.StoreName + "</td>");
                        htmlBuilder.AppendLine("     <td align='center' style='padding:0 5px;'>" + dealerdeposit.FullSetSN + "</td>");
                        htmlBuilder.AppendLine("     <td align='center' style='padding:0 5px;'>" + amount + "</td>");

                    }
                    else
                    {
                        string amount = "0.0";
                        if (type == "out")
                        {
                            amount = dealerdeposit.Amount.ToString("N");
                            var existingDeviceChangelogs =
                            ChangeLogService.GetLastSmdChangeLogs(TaskAPI).Where(t => t.Category == "DepositChange" & t.DataID == dealerdeposit.DeviceID.ToString()).ToList();
                            if (existingDeviceChangelogs.Count > 0)
                            {
                                amount = existingDeviceChangelogs[0].BeforeValue;
                            }
                        }


                        htmlBuilder.AppendLine("<tr>");
                        htmlBuilder.AppendLine("     <td align='center' style='display:none'>[" + dealerdeposit.AuthID + "]" + dealerdeposit.StoreName + "</td>");
                        htmlBuilder.AppendLine("     <td align='center' style='padding:0 5px;'>" + dealerdeposit.FullSetSN + "</td>");
                        htmlBuilder.AppendLine("     <td align='center' style='padding:0 5px;'>" + amount + "</td>");
                    }
                    // 遍历变更类型
                    foreach (var option in options)
                    {
                        var depositTran = depositTrans.FirstOrDefault(t => t.DeviceID == dealerdeposit.DeviceID && t.TranType == option);

                        if (depositTran != null && !string.IsNullOrEmpty(depositTran.TranType))
                        {
                            if (depositTran.Amount == null) continue;
                            var amount = depositTran.Amount.Value.ToString("N");
                            var reason = depositTran.Reason;

                            switch (depositTran.TranType)
                            {
                                case "退至客户银行账号":
                                case "汇入营业外收入":
                                case "转营业外收入":
                                    htmlBuilder.AppendLine("     <td align='center'>" + amount + reason + "</td>");
                                    break;
                                case "进款凭证号码":
                                case "退款凭证号码":
                                    htmlBuilder.AppendLine(TaskAPI.Step == "Finance Change" ? "<td align='center'><input type='text' name='" + type + "_option[" + dealerdeposit.DeviceID + "]' value='" + reason + "' /></td>" : "     <td align='center'>" + reason + "</td>");
                                    break;
                                default:
                                    htmlBuilder.AppendLine("     <td align='center'>" + amount + "</td>");
                                    break;
                            }
                        }
                        else
                        {
                            if (TaskAPI.Step == "Finance Change" && (option == "进款凭证号码" || option == "退款凭证号码"))
                            {
                                htmlBuilder.AppendLine("     <td align='center'><input type='text' name='" + type + "_option[" + dealerdeposit.DeviceID + "]' /></td>");
                            }
                            else
                            {
                                htmlBuilder.AppendLine("     <td align='center'></td>");
                            }
                        }
                    }
                    htmlBuilder.AppendLine("</tr>");
                }
            }



            return htmlBuilder.ToString();
        }

        /// <summary>
        /// 初始化自动发起画面
        /// </summary>
        private string FormatHtml(int dealerId, string type, ICollection<int> deviceIds = null)
        {
            // 获取所有关联数据
            var dealerdeposits = DepositService.FindByDealerIdAndStoreIds(dealerId, null);

            if (deviceIds != null)
            {
                dealerdeposits = dealerdeposits.Where(t => deviceIds.Contains(t.DeviceID)).ToList();
            }

            hf_out_count.Value = hf_in_count.Value = dealerdeposits.Count.ToString(CultureInfo.InvariantCulture);

            // 过滤进款、退款
            var options = type == "in" ? InOptions : OutOptions;

            if (TaskAPI.Step != "Finance Change")
            {
                options.Remove("进款凭证号码");
                options.Remove("退款凭证号码");
            }

            // 生成Html，dealerdeposit=经销商下的每个设备
            var htmlBuilder = new StringBuilder();
            var i = 0;
            foreach (var dealerdeposit in dealerdeposits)
            {
                // 如果是设备三方转移、需要读取一下原来的保证金
                var autoBusinessKey = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");

                if (autoBusinessKey == Constant.PROCESS_TRANSFER && type == "out")
                {
                    var blankVlue = TaskAPI.GetVariableBySingleValue("BlankVlue"); // 选择的设备id | 转出的门店id | 转入的门店id
                    var split = blankVlue.Split('|');

                    var deviceId = split[0];
                    var deposit = (v_DeviceDeposit._DeviceID == deviceId).ListFirst<v_DeviceDeposit>(Storage.Context3,
                        " DepositID desc");
                    if (deposit != null)
                        dealerdeposit.Amount = deposit.Amount ?? 0;

                    var store = StoreService.GetSmdStoreById(Utils.StrToInt(split[1], 0));

                    if (store != null && deposit != null)
                    {
                        dealerdeposit.AuthID = store.AuthID;
                        dealerdeposit.StoreName = store.StoreName;
                    }
                }

                htmlBuilder.AppendLine("<tr>");
                htmlBuilder.AppendLine("     <td align='center' style='display:none'>[" + dealerdeposit.AuthID + "]" + dealerdeposit.StoreName + "</td>");
                htmlBuilder.AppendLine("     <td align='center' style='display:none'>");
                htmlBuilder.AppendLine("        <input type='checkbox' name='" + type + "_checked[" + i + "]' checked='checked' value='" + i + "' />");
                htmlBuilder.AppendLine("        <input type='hidden' name='" + type + "_AuthID[" + i + "]' value='" + dealerdeposit.AuthID + "' />");
                htmlBuilder.AppendLine("        <input type='hidden' name='" + type + "_StoreID[" + i + "]' value='" + dealerdeposit.StoreID + "' />");
                htmlBuilder.AppendLine("        <input type='hidden' name='" + type + "_DeviceID[" + i + "]'  value='" + dealerdeposit.DeviceID + "' />");
                htmlBuilder.AppendLine("     </td>");
                htmlBuilder.AppendLine("     <td align='center' style='padding:0 5px;'>" + dealerdeposit.FullSetSN + "</td>");
                if (type == "in")
                {
                    htmlBuilder.AppendLine("     <td align='center' style='padding:0 5px;'>" + 0.00 + "</td>");
                }
                else
                {
                    htmlBuilder.AppendLine("     <td align='center' style='padding:0 5px;'>" + dealerdeposit.Amount + "</td>");
                }


                // 遍历变更类型
                var j = 0;
                foreach (var option in options)
                {
                    switch (option)
                    {
                        case "退至客户银行账号":
                            htmlBuilder.AppendLine("     <td align='center'>");
                            htmlBuilder.AppendLine("        <input type='text' name='" + type + "_option[" + j + "][" + i + "]' value='0.00' class='isFinanceConfirm'   />");
                            htmlBuilder.AppendLine("        <input type='text' name='" + type + "_payee[" + j + "][" + i + "]' placeholder='请输入收款人' class='isFinanceConfirm'   />");
                            htmlBuilder.AppendLine("        <input type='text' name='" + type + "_account[" + j + "][" + i + "]' placeholder='请输入帐号' class='isFinanceConfirm'   />");
                            htmlBuilder.AppendLine("        <input type='text' name='" + type + "_bank[" + j + "][" + i + "]' placeholder='请输入银行' class='isFinanceConfirm'    />");
                            htmlBuilder.AppendLine("     </td>");
                            break;
                        case "转营业外收入":
                        case "汇入营业外收入":
                            htmlBuilder.AppendLine("     <td align='center'>");
                            htmlBuilder.AppendLine("        <input type='text' name='" + type + "_option[" + j + "][" + i + "]' value='0.00' />");
                            htmlBuilder.AppendLine("        <input type='text' name='" + type + "_remark[" + j + "][" + i + "]' />");
                            htmlBuilder.AppendLine("     </td>");
                            break;
                        default:
                            htmlBuilder.AppendLine("     <td align='center'><input type='text' name='" + type + "_option[" + j + "][" + i + "]' value='0.00' /></td>");
                            break;
                    }
                    j++;
                }
                htmlBuilder.AppendLine("</tr>");
                i++;
            }

            return htmlBuilder.ToString();
        }

        #endregion

        #region 获取保证金变更数据
        private List<t_StoreDepositTran> GetDepositTrans(string assId)
        {
            var depositTrans = new List<t_StoreDepositTran>();
            Logging.GetLogger().Info("GetInDepositTrans_In：Begin");
            depositTrans.AddRange(GetInDepositTrans(assId, "in"));
            Logging.GetLogger().Info("GetInDepositTrans_In：Completed");
            depositTrans.AddRange(GetInDepositTrans(assId, "out"));
            Logging.GetLogger().Info("GetInDepositTrans_out：Completed");

            return depositTrans;
        }
        private IEnumerable<t_StoreDepositTran> GetInDepositTrans(string assId, string type)
        {
            var depositTrans = new List<t_StoreDepositTran>();
            int count;
            // 过滤进款、退款
            List<string> options;
            if (type == "in")
            {
                count = Utils.StrToInt(hf_in_count.Value, 0);
                options = InOptions;
            }
            else
            {
                count = Utils.StrToInt(hf_out_count.Value, 0);
                options = OutOptions;
            }

            Logging.GetLogger().Info(string.Format("1:{0}_{1}", assId, type));

            for (var i = 0; i < count; i++)
            {
                // 没有勾选就跳过
                var _checked = AksRequest.GetFormString(type + "_checked[" + i + "]");

                if (string.IsNullOrEmpty(_checked)) continue;

                var authid = AksRequest.GetFormString(type + "_AuthID[" + i + "]");
                var storeid = AksRequest.GetFormInt(type + "_StoreID[" + i + "]");
                var deviceid = AksRequest.GetFormInt(type + "_DeviceID[" + i + "]");

                // 遍历每一项
                for (var j = 0; j < options.Count; j++)
                {
                    var amount = Utils.StrToDecimal(AksRequest.GetFormString(type + "_option[" + j + "][" + i + "]").Replace(",", ""), 0);
                    var remark = AksRequest.GetFormString(type + "_remark[" + j + "][" + i + "]");
                    var payee = AksRequest.GetFormString(type + "_payee[" + j + "][" + i + "]");
                    var account = AksRequest.GetFormString(type + "_account[" + j + "][" + i + "]");
                    var bank = AksRequest.GetFormString(type + "_bank[" + j + "][" + i + "]");

                    if (amount == 0) continue;

                    var tran = new t_StoreDepositTran
                    {
                        StoreID = storeid,
                        AuthID = authid,
                        DepositType = type == "in" ? "进款" : "退款",
                        TranType = options[j],
                        Amount = amount,
                        TranTime = DateTime.Now,
                        AssessmentID = assId,
                        DeviceID = deviceid
                    };

                    if (key == Constant.PROCESS_CHANGEOTHER)
                    {
                        tran.DepositType = "返还";
                    }

                    switch (tran.TranType)
                    {
                        case "退至客户银行账号":
                            var reason = string.Empty;
                            reason += "/";
                            if (!string.IsNullOrEmpty(payee)) reason = payee;
                            reason += "/";
                            if (!string.IsNullOrEmpty(account)) reason += account;
                            reason += "/";
                            if (!string.IsNullOrEmpty(bank)) reason += bank;
                            tran.Reason = reason;
                            break;
                        case "汇入营业外收入":
                        case "转营业外收入":
                            tran.Reason = remark;
                            break;
                    }

                    depositTrans.Add(tran);
                }

                // 退款需要验证退款金额是否与原金额一致
                if (type == "out")
                {
                    if (depositTrans.All(t => t.DeviceID == deviceid))
                    {
                        var autoBusinessKey = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                        if (!string.IsNullOrEmpty(autoBusinessKey))
                        {
                            var oldDeposit =
                                (t_smd_Deposit._DeviceID == deviceid).ListFirst<t_smd_Deposit>(Storage.Context3,
                                    " DepositID desc");

                            var newDepositValue = depositTrans.Where(t => t.DeviceID == deviceid).Sum(t => t.Amount);


                            //Modified By Tony 20160519
                            decimal oldDepositValue = 0;
                            if (oldDeposit != null)
                            {
                                oldDepositValue = oldDeposit.Amount;
                            }


                            if (key != Constant.PROCESS_CHANGEOTHER)
                            {
                                if (newDepositValue != oldDepositValue)
                                {
                                    var device = DeviceService.GetSmdDeviceById(deviceid);
                                    throw new Exception("对不起，" + device.FullSetSN + "退款金额必须与原保证金一致！");
                                }
                            }
                            else
                            {
                                if (newDepositValue > oldDepositValue)
                                {
                                    var device = DeviceService.GetSmdDeviceById(deviceid);
                                    throw new Exception("对不起，" + device.FullSetSN + "还款金额必须小于原保证金！");
                                }
                                if (oldDepositValue != 0 && newDepositValue == 0)
                                {
                                    var device = DeviceService.GetSmdDeviceById(deviceid);
                                    throw new Exception("对不起，" + device.FullSetSN + "退还总金额不能为0！");
                                }

                            }
                        }
                    }
                }
            }
            if (type == "out")
            {
                if (TaskAPI.Step == "Submit Document")
                {
                    var list = depositTrans.Where(d => d.TranType == "退至客户银行账号").ToList();
                    if (list.Count > 0 && !cb_isFinanceConfirm.Checked)
                    {
                        throw new Exception("您申请了退至客户银行，需要勾选财务确认");
                    }

                    if (list.Count == 0 && cb_isFinanceConfirm.Checked)
                    {
                        throw new Exception("您没有退至客户银行，不能勾选财务确认");
                    }
                }
            }
            return depositTrans;
        }
        #endregion

        #region 方法 提交按钮、数据处理

        /// <summary>
        /// 数据处理方法
        /// </summary>
        /// <param name="returnMsg"></param>
        /// <returns></returns>
        private bool Send(ref string returnMsg)
        {
            var flag = false;
            try
            {
                var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");

                #region 数据验证
                //if (TaskAPI.IsAllowSubmit && TaskAPI.Step == "Finance Change")
                //{
                //    if (!ajaxUpload1.IsUpload && DwzAssessment1.Assessment.Opinion == "1")
                //    {
                //        returnMsg = "请上传相关附件！";
                //        return false;
                //    }
                //}

                if (DwzAssessment1.Assessment.Remark == "")
                {
                    if (DwzAssessment1.Assessment.Opinion == "2")
                    {
                        returnMsg = "如果驳回此流程,请在状态备注中填写放弃流程的原因";
                        return false;
                    }
                    if (DwzAssessment1.Assessment.Opinion == "0")
                    {
                        returnMsg = "如果退回此流程,请在状态备注中填写退回的原因";
                        return false;
                    }
                }

                if (DwzAssessment1.Assessment.Opinion == "3")
                {
                    TaskAPI["ChangeType"] = 1;
                }

                #endregion

                #region 引擎传值
                var inDealer = DealerService.GetById(Utils.StrToInt(uc_dealer_in.dealerId, 0));
                var outDealer = DealerService.GetById(Utils.StrToInt(uc_dealer_out.dealerId, 0));
                var summary = string.Empty;
                if (inDealer != null)
                {
                    summary += "|进" + inDealer.DealerCode;
                }
                if (outDealer != null)
                {
                    summary += "|退" + outDealer.DealerCode;
                }

                if (TaskAPI.IsBeginStep)
                {

                    if (TaskAPI.IsInitiate)
                    {
                        TaskAPI.InitTask(UserAPI, uc_head1.applicationNo);
                    }

                    TaskAPI["TaskID"] = TaskAPI.TaskID;
                    TaskAPI["ChangeType"] = cb_isFinanceConfirm.Checked ? "0" : "1";

                    TaskAPI.Summary = "填写设备保证金变更信息/" + (TaskHelper.getSummary(TaskAPI.Summary) == "" ? "保证金变更" : TaskHelper.getSummary(TaskAPI.Summary)) + summary;
                    if (key == Constant.PROCESS_CHANGEOTHER)
                    {
                        TaskAPI.Summary = "填写设备保证金变更信息/" + (TaskHelper.getSummary(TaskAPI.Summary) == "" ? "保证金批量返还" : TaskHelper.getSummary(TaskAPI.Summary)) + summary;
                    }
                    TaskAPI["Remark_by_Initiator"] = DwzAssessment1.Assessment.Remark;

                    TaskAPI.SetDepositChangeRecipient(AksRequest.GetFormString("ddl_region").ToUpper(),
                        AksRequest.GetFormString("ddl_province"));
                    // 单独发起的，就指定提交人
                    if (string.IsNullOrEmpty(key))
                    {
                        Logging.GetLogger().Info("Store Deposit Change Key：" + key);
                        TaskAPI["R_Submit_Document"] = new object[] { UserAPI.UserName };
                    }
                }
                else
                {
                    TaskAPI["ApproveResult"] = DwzAssessment1.Assessment.Opinion;
                    TaskAPI["TaskID"] = TaskAPI.TaskID;
                    if (TaskAPI.Step == "Submit Document")
                    {
                        TaskAPI["ChangeType"] = cb_isFinanceConfirm.Checked ? "0" : "1";
                        TaskAPI.Summary = "财务审核/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                    }
                    else if (TaskAPI.Step == "Finance Change")
                    {
                        TaskAPI["Changed"] = DwzAssessment1.Assessment.Opinion == "3" ? "1" : DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1" || DwzAssessment1.Assessment.Opinion == "3")
                            TaskAPI.Summary = "财务确认/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                        else
                            TaskAPI.Summary = "(退回)填写设备保证金变更信息/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                    }
                    else if (TaskAPI.Step == "Finance Confirm")
                    {
                        TaskAPI["Confirmed"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                            TaskAPI.Summary = "财务确认/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                        else
                            TaskAPI.Summary = "(退回)财务审核/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                    }
                }
                #endregion

                #region 提交步骤

                Storage.TransactionExecute(o =>
                {
                    #region 审批意见记录

                    var ass = DwzAssessment1.Assessment;
                    var step = "";
                    var lastAss = (t_Assessment.incident == TaskAPI.Incident & t_Assessment.process == TaskAPI.Process).ListFirst<t_Assessment>("time desc");
                    if ((lastAss != null && lastAss.Step != TaskAPI.Step) || lastAss == null)
                    {
                        Logging.GetLogger().Info("开始保存Assessment");
                        Storage.Save(Storage.Context1, ass);
                        Logging.GetLogger().Info("保存Assessment完成");
                    }
                    else
                    {
                        Logging.GetLogger().Info("=================表单已重复提交======================");
                        Logging.GetLogger().Info("TaskAPI.Step:" + TaskAPI.Step);
                        Logging.GetLogger().Info("TaskAPI.UserFullName:" + TaskAPI.UserFullName);
                        Logging.GetLogger().Info("时间：" + DateTime.Now);
                        Logging.GetLogger().Info("UserAPI.UserName:" + UserAPI.UserName);
                        Logging.GetLogger().Info("======================================================");
                        throw new Exception("该表单的步骤已经提交过了，请联系IT。");
                    }

                    #endregion

                    #region “Fill in the form”、“Submit Document”步骤
                    if (TaskAPI.IsBeginStep || TaskAPI.Step == "Submit Document")
                    {
                        var storeMasterData = new t_StoreMasterData
                        {
                            SubmitDate = DateTime.Now,
                            Creator = TaskAPI.UserName,
                            ApplicationNO = uc_head1.applicationNo,
                            DepositType = 1,
                            Process = TaskAPI.Process,
                            Incident = TaskAPI.Incident,
                            AreaName = ddl_region.SelectedValue,
                            ProvinceName = ddl_province.SelectedValue,
                            BusinessProcess = ass.BusinessProcess,
                            BusinessKey = ass.BusinessKey,
                            // 是否需要第二个财务审核
                            PcModel = cb_isFinanceConfirm.Checked.ToString()
                        };

                        // 保存进款经销商
                        if (!string.IsNullOrEmpty(uc_dealer_in.dealerId))
                        {
                            storeMasterData.DispenseModel = uc_dealer_in.dealerId.ToString(CultureInfo.InvariantCulture);
                        }
                        // 保存退款经销商
                        if (!string.IsNullOrEmpty(uc_dealer_out.dealerId))
                        {
                            storeMasterData.ShakerModel = uc_dealer_out.dealerId.ToString(CultureInfo.InvariantCulture);
                        }
                        Logging.GetLogger().Info("开始保存storeMasterData");
                        Storage.Save(Storage.Context1, storeMasterData);
                        Logging.GetLogger().Info("保存storeMasterData完成");

                        Logging.GetLogger().Info("ass.ID：" + ass.ID);
                        var depositTrans = GetDepositTrans(ass.ID);
                        Logging.GetLogger().Info("ass.ID：" + ass.ID);

                        if (depositTrans.Count == 0) throw new Exception("对不起，您没有填写任务数据，不能提交！");
                        // ReSharper disable once CoVariantArrayConversion
                        var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);
                        (t_StoreDepositTran._AssessmentID.In(assIds)).Delete<t_StoreDepositTran>();

                        Storage.Save(depositTrans.ToArray());


                        var deviceIds = depositTrans.Where(t => t.DeviceID != null).Select(t => Convert.ToInt32(t.DeviceID)).Distinct();
                        var devices = DeviceService.FindByDeviceIds(deviceIds.ToList());
                        var storemastrdata = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                        storemastrdata.DeviceFullSetSN = string.Join(",", deviceIds);
                        Storage.Save(Storage.Context1, storemastrdata);
                        var storeIds = depositTrans.Select(t => t.StoreID).Distinct();
                        var stores = StoreService.FindSmdByStoreIds(storeIds.ToList());

                        var fullsetsn = devices.Take(2).OrderByDescending(t => t.DeviceID).Select(t => t.FullSetSN).ToList();
                        var storeTypes = stores.Take(2).Select(t => t.StoreType).ToList();
                        var storeAuthIDs = stores.Take(2).Select(t => t.AuthID).ToList();

                        // 发送邮件提醒时，可以使用
                        //TaskAPI["FullsetSN"] = string.Join(",", fullsetsn) + (fullsetsn.Count > 2 ? "等" : "");
                        //TaskAPI["StoreType"] = string.Join(",", storeTypes) + (storeTypes.Count > 2 ? "等" : "");
                        //TaskAPI["AuthID"] = string.Join(",", storeAuthIDs) + (storeAuthIDs.Count > 2 ? "等" : "");
                        //TaskAPI["Region"] = outDealer.Region;
                        //TaskAPI["Province"] = outDealer.Province;
                        //TaskAPI["BlankVlue"] = outDealer.DealerID;

                        //var oldDealer = DealerService.GetById(Utils.StrToInt(uc_dealer_out.dealerId, 0));
                        //var dealer = DealerService.GetById(Utils.StrToInt(uc_dealer_in.dealerId, 0));
                        //BusinessService.saveProcessRelation(TaskAPI, ass, null, null, dealer, oldDealer, stores, devices, null);

                    }
                    #endregion

                    #region “Finance Change”步骤
                    else if (TaskAPI.Step == "Finance Change")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "1" || DwzAssessment1.Assessment.Opinion == "3")
                        {
                            var assessments = AssessmentService.FindByPI(TaskAPI.Process, TaskAPI.Incident);

                            // 获取所有的保证金变更记录
                            var depositTrans = DepositTranService.FindInAssIds(assessments.Select(t => t.ID).ToList());

                            // 根据设备分组
                            var gDepositTrans = depositTrans.GroupBy(t => t.DeviceID);
                            var list = new List<t_StoreDepositTran>();
                            foreach (var group in gDepositTrans)
                            {
                                var deviceId = group.Key;
                                var depositTran = group.FirstOrDefault();

                                if (depositTran == null) continue;

                                var outOption = AksRequest.GetFormString("out_option[" + depositTran.DeviceID + "]");
                                if (!string.IsNullOrEmpty(outOption))
                                {
                                    var tran = new t_StoreDepositTran
                                    {
                                        StoreID = depositTran.StoreID,
                                        AuthID = depositTran.AuthID,
                                        DepositType = "退款",
                                        TranType = "退款凭证号码",
                                        Amount = 0,
                                        TranTime = DateTime.Now,
                                        AssessmentID = ass.ID,
                                        DeviceID = deviceId,
                                        Reason = outOption
                                    };
                                    if (key == Constant.PROCESS_CHANGEOTHER)
                                    {
                                        tran.DepositType = "返还";
                                    }
                                    list.Add(tran);
                                }

                                var inOption = AksRequest.GetFormString("in_option[" + depositTran.DeviceID + "]");
                                if (!string.IsNullOrEmpty(inOption))
                                {
                                    var tran = new t_StoreDepositTran
                                    {
                                        StoreID = depositTran.StoreID,
                                        AuthID = depositTran.AuthID,
                                        DepositType = "进款",
                                        TranType = "进款凭证号码",
                                        Amount = 0,
                                        TranTime = DateTime.Now,
                                        AssessmentID = ass.ID,
                                        DeviceID = deviceId,
                                        Reason = inOption
                                    };

                                    list.Add(tran);
                                }
                            }
                            // ReSharper disable once CoVariantArrayConversion
                            Storage.Save(list.ToArray());

                            var changeType = TaskAPI.GetVariableBySingleValue("ChangeType");
                            if (changeType == "1" || DwzAssessment1.Assessment.Opinion == "3")
                            {
                                SaveDepositTrans(ass);
                                step = "finish";
                                //记bussinesskey
                                var masterStore = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                                BusinessService.SaveSycnMappingAndBusinesskey(3, masterStore.BusinessKey); 
                            }
                        }
                    }
                    #endregion

                    #region “Fincance Confirm”步骤
                    else if (TaskAPI.Step == "Finance Confirm")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            SaveDepositTrans(ass);
                            step = "finish";
                            //记bussinesskey
                            var masterStore = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                            BusinessService.SaveSycnMappingAndBusinesskey(3, masterStore.BusinessKey); 
                        }
                    }
                    #endregion

                  
                    // 发起失败，就回滚数据
                    flag = TaskAPI.Send();

                    if (TaskAPI.StepStatus("Finish") == 1 || step == "finish")
                    {
                        BusinessService.SaveChildProcess(TaskAPI, DwzAssessment1.Assessment, "Finish");
                    }
                    if (!flag) o.Rollback();

                    #region 关联 实例号

                    if (TaskAPI.IsInitiate || TaskAPI.Step == "Submit Document")
                    {
                        (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == 0).Edit<t_StoreMasterData>(p =>
                        {
                            p.Incident = TaskAPI.Incident;
                        });

                        (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                        {
                            p.Incident = TaskAPI.Incident;
                        });

                        (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 & t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                        {
                            p.Incident = TaskAPI.Incident;
                        });
                    }

                    #endregion

                    #region 自动跳转到财务审核

                    if (!TaskAPI.IsBeginStep) return;
                    System.Threading.Thread.Sleep(2000);
                    var task = TaskHelper.GetTask(TaskAPI.Process, TaskAPI.Incident, "Submit Document");

                    while (task == null)
                    {
                        task = TaskHelper.GetTask(TaskAPI.Process, TaskAPI.Incident, "Submit Document");
                        System.Threading.Thread.Sleep(1000);
                    }
                    var taskapi = new TaskAPI();
                    taskapi.Load(task.strTaskId);
                    taskapi.Send();


                    #endregion
                });
                #endregion
            }
            catch (Exception ex)
            {
                returnMsg = ex.Message.Replace("\"", "\\\"");
                Logging.GetLogger().Error("调用DepositChange.aspx方法Send_Click出错：" + ex.ToString() + "Add By Tony 20160517");
                flag = false;
            }

            return flag;
        }

        /// <summary>
        /// 提交按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_submit_Click(object sender, EventArgs e)
        {
            var returnMsg = string.Empty;
            if (Send(ref returnMsg))
            {
                btn_submit.Visible = false;
                ScriptManager.RegisterStartupScript(this, GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { window.opener.reload(); closeWin(); } });", true);
            }
            else
            {
                returnMsg = string.IsNullOrEmpty(returnMsg) ? Resources.Global.C_00_Failed : returnMsg;
                ScriptManager.RegisterStartupScript(this, GetType(), "info_tip", "$.jBox.prompt('" + returnMsg + "','提示', 'info');", true);
            }
        }

        /// <summary>
        /// 转移保证金变更日志，并且更新保证金
        /// </summary>
        private void SaveDepositTrans(t_Assessment ass)
        {
            var assessments = AssessmentService.FindByPI(TaskAPI.Process, TaskAPI.Incident);
            var depositTrans = DepositTranService.FindInAssIds(assessments.Select(t => t.ID).ToList());

            Mapper.CreateMap<t_StoreDepositTran, t_smd_DepositTran>();
            var list = Mapper.Map<List<t_StoreDepositTran>, List<t_smd_DepositTran>>(depositTrans);

            foreach (t_smd_DepositTran storeDepositTran in list)
            {
                storeDepositTran.EntityState._FieldState.Remove("DepositTranID");
            }

            // 最后一起保存
            // ReSharper disable once CoVariantArrayConversion
            // Storage.Save(Storage.Context3, list.ToArray());

            // 根据 设备id、门店id 区分每条变更的记录
            var items = list.GroupBy(t => new { t.DeviceID, t.StoreID });
            var deposits = new List<t_smd_Deposit>();
            var changeLogs = new List<t_smd_StoreDataChangeLog>();
            var deleteDepositIds = new List<int>();
            foreach (var item in items)
            {
                //deleteDepositId.Add()

                var autoBusinessKey = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");

                var gKey = item.Key;
                var gDepositTrans = item.ToList();

                var lOut = gDepositTrans.Where(t => t.DepositType == "退款").Sum(t => t.Amount).Value;
                if (key == Constant.PROCESS_CHANGEOTHER)
                {
                    lOut = gDepositTrans.Where(t => t.DepositType == "返还").Sum(t => t.Amount).Value;
                }
                var lIn = gDepositTrans.Where(t => t.DepositType == "进款").Sum(t => t.Amount).Value;

                var deposit = DepositService.GetDeviceDeposit(gKey.StoreID, gKey.DeviceID.Value);
                var store = StoreService.GetSmdStoreById(gKey.StoreID);
                if (deposit == null)
                {


                    deposit = new t_smd_Deposit
                    {
                        StoreID = gKey.StoreID,
                        DeviceID = gKey.DeviceID.Value,
                        AuthID = store.AuthID,
                        DepositType = "设备保证金",
                        PostingDate = DateTime.Now,
                        DealerId = store.DealerID.Value
                    };

                    // 如果是新纪录，把以前的保证金删掉
                    var deviceDeposits =
                        (t_smd_Deposit._DeviceID == deposit.DeviceID & t_smd_Deposit._DepositType == "设备保证金")
                            .List<t_smd_Deposit>(Storage.Context3);
                    deleteDepositIds.AddRange(deviceDeposits.Select(t => t.DepositID).ToList());
                }

                deposit.Amount = deposit.Amount + (lIn - lOut);

                // 如果是经销商变更、设备三方转移，就直接覆盖
                if (autoBusinessKey == Constant.PROCESS_CHANGEDEALER || autoBusinessKey == Constant.PROCESS_TRANSFER)
                {
                    deposit.Amount = lIn;
                    deposit.DealerId = store.DealerID.Value;
                }

                deposits.Add(deposit);

                var deviceDeposit = (t_smd_Deposit._DeviceID == deposit.DeviceID & t_smd_Deposit._DepositType == "设备保证金").ListFirst<t_smd_Deposit>(Storage.Context3, " DepositID desc");
                var changeLog = new t_smd_StoreDataChangeLog();
                changeLog.Category = "DepositChange";
                changeLog.DataID = deposit.DeviceID.ToString();
                changeLog.FieldName = "Amount";
                changeLog.BeforeValue = (deviceDeposit == null ? 0 : deviceDeposit.Amount).ToNullSafeString();
                changeLog.AfterValue = deposit.Amount.ToString();
                changeLog.ChangeTime = DateTime.Now;
                changeLog.UserID = ass.AssignedToUserFullName;
                changeLog.AssessmentID = ass.ID;
                changeLogs.Add(changeLog);

            }

            Storage.Save(Storage.Context3, changeLogs.ToArray());
            Storage.Save(Storage.Context3, list.ToArray());
            Storage.Save(Storage.Context3, deposits.ToArray());

            // 清楚设备保证金冗余数据
            if (deleteDepositIds.Count > 0)
            {
                t_smd_Deposit._DepositID.In(deleteDepositIds).Delete<t_smd_Deposit>(Storage.Context3);
            }
        }

        #endregion

        #region 方法 获取

        /// <summary>
        /// 从“经销商更换流程”中获取“被更换的经销商”下历史设备
        /// </summary>
        /// <returns></returns>
        private List<int> GetDeviceIds()
        {
            var ids = new List<int>();
            if (key != Constant.PROCESS_CHANGEOTHER)
            {
                // 获取经销商变更流程的业务数据
                var parentProcess = TaskAPI.GetVariableBySingleValue("ParentProcess");
                var parentIncident = TaskAPI.GetVariableBySingleValue("ParentIncident");
                var parentStoreMasterData = StoreMasterDataService.GetByPI(parentProcess,
                    Utils.StrToInt(parentIncident, 0));

                // 从 “DispenseModel” 字段获取设备id，多个设备用以字符 “,” 隔开
                if (string.IsNullOrEmpty(parentStoreMasterData.DispenseModel)) return ids;
                var deviceids = parentStoreMasterData.DispenseModel.Split(',');
                ids.AddRange(deviceids.Select(deviceid => Utils.StrToInt(deviceid, 0)));
            }
            else
            {
                var storeMasterdata = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                var deviceids = storeMasterdata.DeviceFullSetSN.Split(',');
                ids.AddRange(deviceids.Select(deviceid => Utils.StrToInt(deviceid, 0)));
            }

            return ids;
        }
        #endregion

        #region 事件 切换地区

        /// <summary>
        /// 切换地区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddl_region_SelectedIndexChanged(object sender, EventArgs e)
        {
            var region = ddl_region.SelectedValue;

            ddl_province.Items.Clear();
            ddl_province.Items.Add(new ListItem("==请选择==", ""));

            if (!string.IsNullOrEmpty(region))
            {

                var configService = new ConfigService();
                var dt = configService.GetList("ParentId = (select configid from t_smd_Config where [level] = 1 and name='" + region + "' ) order by seq").Tables[0];
                ddl_province.AppendDataBoundItems = true;
                ddl_province.DataValueField = "Name";
                ddl_province.DataTextField = "Name";
                ddl_province.DataSource = dt;
                ddl_province.DataBind();
            }
        }

        #endregion
    }
}